package com.mm.util.note;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.mm.domain.quartz.ExcelTitleAlias;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 描述: Excel 导入导出工具类
 *
 * @author: yanglin
 * @Date: 2021-07-19-11:17
 * @Version: 1.0
 */
public class ExcelExImUtil {

    /**
     * 导出excel
     * @param response
     * @param fileName 文件名称
     * @param excelTitleAlias 字段名称集合
     * @param data
     * @param <E>
     */
    public static <E> void exportExcel(HttpServletResponse response, String fileName, List<ExcelTitleAlias> excelTitleAlias, List<E> data) {
        ExcelWriter writer = ExcelUtil.getWriter();
        for (int i = 0; i < excelTitleAlias.size(); i++) {
            ExcelTitleAlias titleAlias = excelTitleAlias.get(i);
            writer.addHeaderAlias(titleAlias.getTitle(), titleAlias.getAlias());
        }
        writer.write(data, true);
        try {
            fileName = new String((fileName + ".xls").getBytes(), "ISO-8859-1");
            response.setHeader("content-Type", "application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            // 将Excel写入到response的输出流中，并关闭输出流
            writer.flush(response.getOutputStream(), true);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }
    }
}
